const express = require('express');
const { body, param } = require('express-validator');
const PaymentController = require('../controllers/paymentController');
const { authenticateToken, requireAdmin } = require('../middleware/auth');
const { logger } = require('../utils/logger');
const router = express.Router();

// 创建支付控制器实例
const paymentController = new PaymentController();

// 验证规则
const createPaymentValidation = [
  body('orderId')
    .isInt({ min: 1 })
    .withMessage('订单ID必须是正整数'),
  body('paymentMethod')
    .isIn(['alipay', 'wechat', 'apple_pay', 'google_pay', 'cash', 'card'])
    .withMessage('支付方式无效')
];

const confirmPaymentValidation = [
  body('orderId')
    .isInt({ min: 1 })
    .withMessage('订单ID必须是正整数')
];

const cardPaymentValidation = [
  body('orderId')
    .isInt({ min: 1 })
    .withMessage('订单ID必须是正整数'),
  body('transactionId')
    .optional()
    .isString()
    .isLength({ min: 1, max: 100 })
    .withMessage('交易ID格式无效')
];

const applePayValidation = [
  body('orderId')
    .isInt({ min: 1 })
    .withMessage('订单ID必须是正整数'),
  body('paymentToken')
    .isObject()
    .withMessage('Apple Pay支付令牌格式无效')
];

const googlePayValidation = [
  body('orderId')
    .isInt({ min: 1 })
    .withMessage('订单ID必须是正整数'),
  body('paymentToken')
    .isObject()
    .withMessage('Google Pay支付令牌格式无效')
];

const orderIdValidation = [
  param('orderId')
    .isInt({ min: 1 })
    .withMessage('订单ID必须是正整数')
];

// ==================== 用户支付接口 ====================

/**
 * @route   POST /api/payments/create
 * @desc    创建支付订单
 * @access  Private (需要登录)
 * @body    { orderId: number, paymentMethod: string }
 */
router.post('/create', 
  authenticateToken,
  createPaymentValidation,
  (req, res) => paymentController.createPayment(req, res)
);

/**
 * @route   GET /api/payments/methods
 * @desc    获取支持的支付方式
 * @access  Private (需要登录)
 */
router.get('/methods',
  authenticateToken,
  (req, res) => paymentController.getPaymentMethods(req, res)
);

/**
 * @route   GET /api/payments/status/:orderId
 * @desc    查询支付状态
 * @access  Private (需要登录)
 * @params  orderId - 订单ID
 */
router.get('/status/:orderId',
  authenticateToken,
  orderIdValidation,
  (req, res) => paymentController.getPaymentStatus(req, res)
);

// ==================== 支付回调接口 ====================

/**
 * @route   POST /api/payments/alipay/notify
 * @desc    支付宝支付回调
 * @access  Public (支付宝回调)
 */
router.post('/alipay/notify',
  (req, res) => paymentController.alipayNotify(req, res)
);

/**
 * @route   POST /api/payments/wechat/notify
 * @desc    微信支付回调
 * @access  Public (微信支付回调)
 */
router.post('/wechat/notify',
  (req, res) => paymentController.wechatNotify(req, res)
);

// ==================== 移动支付验证接口 ====================

/**
 * @route   POST /api/payments/apple-pay/verify
 * @desc    Apple Pay支付验证
 * @access  Private (需要登录)
 * @body    { orderId: number, paymentToken: object }
 */
router.post('/apple-pay/verify',
  authenticateToken,
  applePayValidation,
  (req, res) => paymentController.applePayVerify(req, res)
);

/**
 * @route   POST /api/payments/google-pay/verify
 * @desc    Google Pay支付验证
 * @access  Private (需要登录)
 * @body    { orderId: number, paymentToken: object }
 */
router.post('/google-pay/verify',
  authenticateToken,
  googlePayValidation,
  (req, res) => paymentController.googlePayVerify(req, res)
);

// ==================== 线下支付确认接口 ====================

/**
 * @route   POST /api/payments/cash/confirm
 * @desc    现金支付确认
 * @access  Private (需要登录或管理员权限)
 * @body    { orderId: number }
 */
router.post('/cash/confirm',
  authenticateToken,
  confirmPaymentValidation,
  (req, res) => paymentController.confirmCashPayment(req, res)
);

/**
 * @route   POST /api/payments/card/confirm
 * @desc    刷卡支付确认
 * @access  Private (需要登录或管理员权限)
 * @body    { orderId: number, transactionId?: string }
 */
router.post('/card/confirm',
  authenticateToken,
  cardPaymentValidation,
  (req, res) => paymentController.confirmCardPayment(req, res)
);

// ==================== 管理员支付管理接口 ====================

/**
 * @route   GET /api/payments/admin/transactions
 * @desc    获取所有交易记录（管理员）
 * @access  Private (管理员)
 * @query   page, limit, status, method, startDate, endDate
 */
router.get('/admin/transactions',
  authenticateToken,
  requireAdmin,
  async (req, res) => {
    try {
      const {
        page = 1,
        limit = 20,
        status,
        method,
        startDate,
        endDate
      } = req.query;

      // 这里应该调用相应的服务方法获取交易记录
      // 暂时返回模拟数据
      const transactions = {
        total: 0,
        page: parseInt(page),
        limit: parseInt(limit),
        data: []
      };

      res.json({
        success: true,
        message: '获取交易记录成功',
        data: transactions
      });

    } catch (error) {
      logger.error('获取交易记录失败:', error);
      res.status(500).json({
        success: false,
        message: '获取交易记录失败',
        error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
      });
    }
  }
);

/**
 * @route   GET /api/payments/admin/statistics
 * @desc    获取支付统计数据（管理员）
 * @access  Private (管理员)
 * @query   startDate, endDate
 */
router.get('/admin/statistics',
  authenticateToken,
  requireAdmin,
  async (req, res) => {
    try {
      const { startDate, endDate } = req.query;

      // 这里应该调用相应的服务方法获取统计数据
      // 暂时返回模拟数据
      const statistics = {
        totalAmount: 0,
        totalTransactions: 0,
        successRate: 0,
        methodBreakdown: {
          alipay: { count: 0, amount: 0 },
          wechat: { count: 0, amount: 0 },
          apple_pay: { count: 0, amount: 0 },
          google_pay: { count: 0, amount: 0 },
          cash: { count: 0, amount: 0 },
          card: { count: 0, amount: 0 }
        },
        dailyTrend: []
      };

      res.json({
        success: true,
        message: '获取支付统计成功',
        data: statistics
      });

    } catch (error) {
      logger.error('获取支付统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取支付统计失败',
        error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
      });
    }
  }
);

/**
 * @route   POST /api/payments/admin/refund
 * @desc    处理退款（管理员）
 * @access  Private (管理员)
 * @body    { orderId: number, amount?: number, reason: string }
 */
router.post('/admin/refund',
  authenticateToken,
  requireAdmin,
  [
    body('orderId')
      .isInt({ min: 1 })
      .withMessage('订单ID必须是正整数'),
    body('amount')
      .optional()
      .isFloat({ min: 0.01 })
      .withMessage('退款金额必须大于0'),
    body('reason')
      .isString()
      .isLength({ min: 1, max: 500 })
      .withMessage('退款原因不能为空且不超过500字符')
  ],
  async (req, res) => {
    try {
      const { orderId, amount, reason } = req.body;
      const adminId = req.user.id;

      // 这里应该调用相应的服务方法处理退款
      // 暂时返回模拟数据
      const refundResult = {
        success: true,
        refundId: `refund_${Date.now()}`,
        orderId: orderId,
        amount: amount,
        reason: reason,
        processedBy: adminId,
        processedAt: new Date()
      };

      res.json({
        success: true,
        message: '退款处理成功',
        data: refundResult
      });

    } catch (error) {
      logger.error('退款处理失败:', error);
      res.status(500).json({
        success: false,
        message: '退款处理失败',
        error: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
      });
    }
  }
);

module.exports = router;